"use client";

import { usePathname } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import Forbidden from "@/app/forbidden";
import { MenuDataItem } from "@ant-design/pro-layout";

// 根据路径查找菜单（递归）
const findMenuItemByPath = (
  menus: MenuDataItem[],
  path: string,
): MenuDataItem | null => {
  for (const menu of menus) {
    if (menu.path === path) {
      return menu;
    }
    if (menu.children) {
      const matchedMenuItem = findMenuItemByPath(menu.children, path);
      if (matchedMenuItem) {
        return matchedMenuItem;
      }
    }
  }
  return null;
};

// 根据全部路径查找菜单
const findAllMenuItemByPath = (path: string): MenuDataItem | null => {
  const menus = [
    {
      path: "/",
      name: "首页",
    },
    {
      path: "/bank",
      name: "题库",
    },
    {
      path: "/question",
      name: "题目",
    },
    {
      path: "/oj",
      name: "去 OJ 练习广场",
      isExternal: true,
    },
  ] as MenuDataItem[];
  return findMenuItemByPath(menus, path);
};

/**
 * 统一权限校验拦截器
 * @param children
 * @constructor
 */
const AccessLayout: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  const pathname = usePathname();
  // 当前登录用户
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 获取当前路径需要的权限
  const menu = findAllMenuItemByPath(pathname);
  const needAccess = menu?.access ?? ACCESS_ENUM.NOT_LOGIN;
  // 校验权限
  const canAccess = checkAccess(loginUser, needAccess);
  if (!canAccess) {
    return <Forbidden />;
  }
  return children;
};

export default AccessLayout;
